package xing.example.converter.factory;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import xing.example.bean.A;
import xing.example.bean.Alpha;

import java.lang.reflect.InvocationTargetException;

/**
 * @author xing
 * @date 2023/2/16 1:06:26
 */
public class StringToAConverterFactory implements ConverterFactory<String, Alpha> {

    @Override
    public <T extends Alpha> Converter<String, T> getConverter(Class<T> targetType) {
        return new StringToAlphaConverter<>(targetType);
    }

    private final class StringToAlphaConverter<T extends Alpha> implements Converter<String, T> {
        Class<T> clazz;
        public StringToAlphaConverter(Class<T> clazz) {
            this.clazz = clazz;
        }

        @Override
        public T convert(String source) {
            // 也可以 return clazz.cast(new A(Integer.parseInt(source)));
            // 或 return (T) new A (Integer.parseInt(source));
            try {
                // return clazz.getConstructor(int.class).newInstance(Integer.parseInt(source) + 3);
                return clazz.getConstructor(int.class).newInstance(Integer.parseInt(source));
            } catch (InstantiationException | IllegalAccessException | InvocationTargetException |
                     NoSuchMethodException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
